﻿using System.Threading;
using System.Threading.Tasks;
using JT808.Gateway.Abstractions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace JT808.Gateway.QueueServer.Custom
{
    public class JT808ApiResponseHostedService : IHostedService
    {
        IJT808ApiResponseConsumer Consumer { get; }
        IJT808WebApiService WebApiService { get; }
        ILogger Logger { get; }
        public JT808ApiResponseHostedService(IJT808ApiResponseConsumer consumer,
            IJT808WebApiService webApiService,
            ILoggerFactory factory)
        {
            Consumer = consumer;
            WebApiService = webApiService;
            Logger = factory.CreateLogger<JT808ApiResponseHostedService>();
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            Consumer.OnMessage((item) =>
            {
                if (!WebApiService.CachedResponse.TryAdd(item.TerminalNo, item.Data))
                {
                    Logger.LogError($"id={item.TerminalNo}, Faild to add to CachedResponse");
                }
                else
                {
                    Logger.LogError($"id={item.TerminalNo}, Successfully add to CachedResponse");
                }
            });
            Consumer.Subscribe();
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            Consumer.Unsubscribe();
            return Task.CompletedTask;
        }
    }
}
